const router = require('express').Router()
const sql = require('../sql')
const teststore = require('../sql/models/Teststore')
const utils = require('../utils')
const xlsx = require('node-xlsx')
const urlencode = require('urlencode')
const fs = require('fs')
const path = require('path')
var multer = require('multer')
var upload = multer({ dest: './public/uploads/' })

//导出试题模板
router.get('/exportTestPaperModel', (req, res, next) => {
  let testPaperModel = []
  // 给表格设置头部
  testPaperModel.unshift([
    '题目',
    '答案选择（如单选题选项用‘/’隔开）',
    '分类(例：网络工程)',
    '难易等级(从A开始难度逐渐降低，最低为C)',
    '题目类型（1：单选题，2：填空题，3：简答题）',
    '分值',
    '正确答案（填具体内容）',
  ])
  // 写入到excel文件中
  let buffer = xlsx.build([
    { name: 'testPaperModel.xlsx', data: testPaperModel },
  ])
  // 设置响应头
  res.setHeader('Content-Type', 'application/octet-stream')
  // 设置文件名字
  let name = urlencode('试题模板_' + +new Date() + '.xlsx', 'utf-8')
  res.setHeader('Content-Disposition', "attachment; filename* = UTF-8''" + name)
  res.send(buffer)
})

// 向数据库中导入文件
router.post(
  '/uploadTestPaperStore',
  upload.single('file'),
  (req, res, next) => {
    const file = req.file

    res.header('Content-Type', 'multipart/form-data')
    if (file) {
      fs.renameSync(
        path.join('./public/uploads', file.filename),
        path.join('./public/uploads', file.filename + '.xlsx')
      )
      // 设置存储的地址
      const url = path.join(
        __dirname,
        `/../public/uploads/${file.filename}.xlsx`
      )
      // 解析表格中的数据
      const originData = xlsx.parse(url)[0].data
      const insertData = []
      originData.forEach((item, index) => {
        if (index !== 0) {
          // 分割表格中数据 处理为数组传入数据库
          const answer = item[1].split('/')
          const answerArr = answer.map((item) => {
            return item.trim()
          })
          insertData.push({
            teststoreid: 'teststore_' + utils.getUuid(),
            questiontitle: item[0].trim(),
            answer: answerArr,
            category: item[2].trim(),
            diflevel: item[3].trim(),
            type: item[4],
            score: item[5],
            correntanswer: item[6].trim(),
          })
          console.log(insertData)
        }
      })
      //  向数据库中插入数据
      sql.insert(teststore, insertData).then(() => {
        // 设置响应头
        res.header('Content-Type', 'multipart/form-data')
        res.status(200).send({
          code: 200,
          message: '上传数据成功',
        })
      })
    }
  }
)
// 获取试题库中的列表
router.get('/getTestSroreList', (req, res, next) => {
  sql.find(teststore, {}, { __v: 0 }).then((data) => {
    res.status('200').send({
      code: '200',
      message: '获取题库列表',
      data,
    })
  })
})
module.exports = router
